#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, time, getopt, traceback, shutil, rpm
from popen2 import Popen3
from threadpool import * 
from functions import *

class Doc4():

    def __init__(self, distrib, arch, branch, section, inputdir, outputdir, metadata_only, log):
        self.distrib_id = distrib
        self.arch = arch
        self.branch = branch
        self.section = section
        self.inputdir = inputdir
        self.outputdir = outputdir
        self.log = log
        self.metadata_only = metadata_only
        
    def extract_packages(self):
        extracted_ones = self.list_already_extracted_packages()
        
        packages = []
        for root, dirs, files in os.walk(self.inputdir):
            for package in files:
                if not(os.path.isdir(package)) and package.endswith('.rpm') and not(package in extracted_ones):
                    packages.append(package)
        print "Number of packages to be processed: %s" % len(packages) 
        packages.sort()
        for package in packages:
            command = 'python $MPHS_PKG_EXTRACTION/package-extractor.py'+' -p ' + package + ' -d ' + self.distrib_id+' -a '+self.arch+' -b '+self.branch+' -s '+self.section+' -i '+self.inputdir+' -o '+self.outputdir+' -l '+self.log
            if self.metadata_only == 'true':
                command = command+' --metadata-only'
            print command
            pid = Popen3(command)
            result = pid.wait()
            #commented out when no threading
            #return result
            
    def list_already_extracted_packages(self):
        packages = []
        for dir in os.listdir(self.outputdir):
            if dir.endswith('.rpm'):
                packages.append(dir)
        return packages
            
usage = "package-list-extractor.py --distrib=[distrib] --arch=[arch] --branch=[branch] --section=[section] --inputdir=[inputdir-path] --outputdir=[outputdir-path] --metadata-only=[true|false] --log=[log-file]"

example = "python package-list-extractor.py --distrib=cooker --arch=i586 --branch=main --section=release --inputdir=/home/arkub/tmp/ --outputdir=/home/arkub/tmp/ --log=/home/arkub/mphs.log --metadata-only=false"

try:
    opts, args = getopt.getopt(sys.argv[1:], "h:c:d:a:b:s:i:o:m:l:", ["help", "config=", "distrib=", "arch=", "branch=", "section=", "inputdir=", "outputdir=", "log=", "metadata-only="])
except getopt.GetoptError:
    print 'Invalid option. Usage :'
    print "%s" % usage
    sys.exit(2)

for opt, arg in opts:
    if opt in ("-h", "--help"):
        print 'Usage: %s' % usage
        sys.exit(0)
    elif opt in ("-d","--distrib"):
        distrib = arg
    elif opt in ("-a","--arch"):
        arch = arg
    elif opt in ("-b","--branch"):
        branch = arg
    elif opt in ("-s","--section"):    
        section = arg
    elif opt in ("-i","--inputdir"):
        inputdir = arg
    elif opt in ("-o","--outputdir"):
        outputdir = arg
    elif opt in ("-m","--metadata-only"):
        metadata_only = arg
    elif opt in ("-l","--log"):
        log = os.path.abspath(arg)
    
    
try:
    if vars().has_key('outputdir'):
        log_package("\n== Extracting packages ==\n", log)
        log_package("Distribution: %s - Input: %s - Output: %s\n" % (distrib,inputdir,outputdir), log)
        doc4 = Doc4(distrib, arch, branch, section, inputdir, outputdir, metadata_only, log)
        print 'Launching extraction...\nDistribution: %s\nInput directory: %s\nOutput directory: %s' % (distrib,inputdir,outputdir)
        if (not os.access(outputdir, os.F_OK)):
            os.mkdir(outputdir)
        doc4.extract_packages()
        
    else:
        print "Some options are missing.\nUsage:\n%s" % usage
        print "Example:\n%s" % example
        sys.exit(1)
    
except KeyboardInterrupt:
    #doc4.db.close()
    sys.exit(0)
except Exception, e:
    traceback.print_exc(file=sys.stdout)
    #doc4.db.close()
    sys.exit(0)

    